package cn.yikaojiuguo.student.support.utils;


import org.json.JSONObject;

import cn.yikaojiuguo.student.app.YiKaoApplication;
import cn.yikaojiuguo.student.support.volley.Request;
import cn.yikaojiuguo.student.support.volley.RequestQueue;
import cn.yikaojiuguo.student.support.volley.Response;
import cn.yikaojiuguo.student.support.volley.toolbox.JsonObjectRequest;

/**
 * Created by cfan_yang on 2015/12/11.
 * 对Volley进行封装的工具类
 */
public class RequestUtil {

    private static RequestQueue mQueue = YiKaoApplication.getRequestQueue();

    /**
     * Get请求
     *
     * @param url           请求url
     * @param listener      请求成功的回调
     * @param errorListener 请求失败的回调
     * @param tag           请求对应的标签
     * @param needCache     是否需要缓存
     */
    public static void requestGet(String url, Response.Listener<JSONObject> listener, Response
            .ErrorListener errorListener, String tag, boolean needCache) {
        if (!url.contains("http://")) {
            LogUtil.showErrorLog(tag, url + "does't contain http://");
            return;
        }
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                listener, errorListener,needCache);
        request.setTag(tag);
        mQueue.add(request);
    }

    /**
     * Get请求
     *
     * @param url           请求url
     * @param listener      请求成功的回调
     * @param errorListener 请求失败的回调
     * @param tag           请求对应的标签
     */
    public static void requestGet(String url, Response.Listener<JSONObject> listener, Response
            .ErrorListener errorListener, String tag) {
        requestGet(url, listener, errorListener, tag, false);
    }

    /**
     * 取消请求
     */
    public static void cancelRequest(String tag) {
        mQueue.cancelAll(tag);
    }

    /**
     * 取消请求回调
     */
    public static void cancelRequest(RequestQueue.RequestFinishedListener<?> listener) {
        mQueue.removeRequestFinishedListener(listener);
    }

}
